package com.example.intermediateactivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;


import com.example.intermediateactivity.R;
import com.example.intermediateactivity.database.ShoppingCartDBHelper;
import com.example.intermediateactivity.entity.GoodsInfo;
import com.example.intermediateactivity.utils.ToastHelper;

import org.w3c.dom.Text;

import java.util.List;

public class ShoppingCart extends AppCompatActivity implements View.OnClickListener {

    private ShoppingCartDBHelper dbHelper;
    private TextView tv_count;
    private GridLayout gl_channel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Log.d("zhoutao", "MainActivity.onCreate: ");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);

        // 设置标题
        TextView tv_Title = findViewById(R.id.tv_title);
        tv_Title.setText("手机商城");

        // topbar 返回和购物车按钮点击事假
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_cart).setOnClickListener(this);

        tv_count = findViewById(R.id.tv_count);
        // 商品容器-grid布局
        gl_channel = findViewById(R.id.gl_channel);


        // 打开数据库连接
        dbHelper = ShoppingCartDBHelper.getInstance(this);
        dbHelper.openWriteLink();
        dbHelper.openReadLink();

        // 查询出所有商品信息
        showGoods();
    }

    private void showGoods() {
        // 获取屏幕宽度，用于设置shopping_goods_item.xml商品信息宽度为屏幕宽度的一半
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        // 创建layout参数对象，设置layout宽高
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(screenWidth / 2, ViewGroup.LayoutParams.WRAP_CONTENT);

        // 先清空子元素-移除所有商品组件
        gl_channel.removeAllViews();

        List<GoodsInfo> goodsInfoList = dbHelper.queryAllGoodsInfo();
        for (GoodsInfo info : goodsInfoList) {
            // 获取shopping_goods_item.xml对象
            View view = LayoutInflater.from(this).inflate(R.layout.activity_shopping_goods_item, null);

            // 通过根对象获取子元素，设置手机名称
            TextView tvGoodsName = view.findViewById(R.id.tv_goods_name);
            tvGoodsName.setText(info.name);
            // 通过根对象获取子元素，设置手机价格
            TextView tvGoodsPrice = view.findViewById(R.id.tv_goods_price);
            tvGoodsPrice.setText(String.valueOf((int) info.price));
            // 通过根对象获取子元素，手机图片
            ImageView ivGoodsImage = view.findViewById(R.id.iv_goods_image);
            // 设置手机图片
            ivGoodsImage.setImageURI(Uri.parse(info.picPath));

            // 给所有添加到购物车按钮添加点击事件
            Button btn_addToCard = view.findViewById(R.id.btn_add_to_cart);
            btn_addToCard.setOnClickListener(v -> {
                addToCart(info.id, info.name);
            });

            // 点击图片跳转详情
            ivGoodsImage.setOnClickListener(v -> {
                Intent intent = new Intent(ShoppingCart.this, GoodsDetial.class);
                intent.putExtra("goods_id", info.id);
                startActivity(intent);
            });

            // 将shopping_goods_item添加到商品容器（grid-layout）中, 并设置宽高
            gl_channel.addView(view, layoutParams);
        }

    }

    private void addToCart(int goodsId, String goodsName) {
        Log.d("zhoutao", "goodsId: " + goodsId + ", goodsName: " + goodsName);
        // 购物车表中添加商品
        dbHelper.insertCartInfo(goodsId);
        // 购物车中商品数量图标加1
        int count = ++MyApplication.getInstance().goodsCountInCart;
        tv_count.setText(String.valueOf(count));

        ToastHelper.show(this, goodsName + "已添加到购物车");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

        // 获取购物车中的商品数量
        setCountTextView();
    }

    private void setCountTextView() {
        int count = dbHelper.countOfCartInfo();

        tv_count.setText(String.valueOf(count));
        MyApplication.getInstance().goodsCountInCart = count;
    }

    @Override
    protected void onStart() {
        Log.d("zhoutao", "MainActivity.onStart: ");
        super.onStart();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        dbHelper.closeLink();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        // 点击返回
        if (R.id.iv_back == id) {
            finish();  // 退出应用
        } else if (R.id.iv_cart == id) {
            // 点击购物车，跳转购物车页面
            Intent intent = new Intent(this, CartCountActivity.class);
            // 设置单页面模式，每次清空该页面顶部
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }
}